package com.huiquan.vocab.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.synonymy.dao.SynonymyDao;
import com.huiquan.synonymy.dao.SynonymyWordDao;
import com.huiquan.synonymy.domain.Synonymy;
import com.huiquan.synonymy.domain.SynonymyWord;

@Service
public class VocabElementRService extends BaseService {
	@Autowired
	private SynonymyDao synonymyDao;
	@Autowired
	private SynonymyWordDao synonymyWordDao;

	/**
	 * 校验r同义词 去除错误小词r的同义词
	 */
	public ReturnData initRSynonymy() {
		List<SynonymyWord> deleteValues = synonymyWordDao.checkRSynonymy();
		for (SynonymyWord deleteValue : deleteValues) {
			deleteSynonymy(deleteValue);
		}
		return ReturnUtil.success();
	}

	/**
	 * 删除同义词
	 */
	private void deleteSynonymy(SynonymyWord deleteValue) {
		long id = deleteValue.getSynonymyId();
		String word = deleteValue.getWord();
		Synonymy synonymy = synonymyDao.retrieveObjectById(id);
		if(synonymy != null){
			synonymy.setWords(synonymy.getWords().replace(word + "\t", ""));
			if(synonymy.getWords().split("\t").length<3){
				synonymyDao.delete(id);
				synonymyWordDao.deleteBySynonymyId(id);
			}else{
				if (StringUtils.equals(synonymy.getStd(), word)) {
					String newStd = (synonymy.getWords().split("\t"))[1];
					synonymy.setStd(newStd);
					String reg = "^[u0391-uFFE5/!@#$%^&*()_+-=,./;\\<>?:{}|`~]*$";
					if (newStd.matches(reg)) {
						synonymy.setEnglishStd(newStd);
						synonymy.setChineseStd("");
					} else {
						synonymy.setEnglishStd("");
						synonymy.setChineseStd(newStd);
					}
					synonymy.setModifierId(1L);
					synonymy.setModifierName("系统管理员");
				}
				synonymyDao.update(synonymy);
				synonymyWordDao.delete(deleteValue);
			}
		}
	}

}
